<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 * 用户账号
 */
class SocialAccount extends Model
{
    protected $table = 'social_account';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'provider', 'provider_user_id'
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 查找记录
     */
    static function check($provider = 'weixin', $providerId = '')
    {
        return self::where(['provider' => $provider, 'provider_user_id' => $providerId])->first();
    }

    /**
     * 查找用户记录
     */
    static function checkUser($provider = 'weixin', $userId = 0)
    {
        return self::where(['provider' => $provider, 'user_id' => $userId])->first();
    }

    /**
     * 解绑第三方账号
     */
    static function unbind($provider = 'weixin', $userId = 0)
    {
        return self::where(['provider' => $provider, 'user_id' => $userId])->limit(1)->delete();
    }

    /**
     * 创建第三方账号
     */
    static function createAccount($userId = 0, $provider = 'weixin', $providerId = '')
    {
        return self::create([
            'user_id' => $userId,
            'provider' => $provider,
            'provider_user_id' => $providerId,
        ]);
    }
}
